const Router = require("koa-router");
const { Alioss } = require("@services/alioss");
const { User } = require("@models/user");
const { Auth } = require("@middlewares/auth");
const { redis } = require("@core/redis");
const { IdCard } = require("@models/idcard");
const Op = require("sequelize").Op;

const router = new Router({
  prefix: "/admin/user",
});

// 获取用户列表
router.post("/list", new Auth(16).m, async (ctx, next) => {
  const {
    page = 1,
    pageSize = 10,
    user_name,
    phone,
    login_at,
  } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  // 查询条件
  const where = {
    user_name: { [Op.like]: `%${user_name}%` },
    phone: { [Op.like]: `%${phone}%` },
  };

  // const where = {
  //   [Op.or]: [
  //     { user_name: { [Op.like]: `%${user_name || ""}%` } },
  //     { phone: { [Op.like]: `%${phone || ""}%` } },
  //   ],
  // };
  let order = [];
  if (login_at) {
    order = [
      ["login_at", "desc"],
      ["created_at", "desc"],
    ];
  } else {
    order = [["created_at", "desc"]];
  }

  const { count: total, rows } = await User.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order, // 排序
    include: [
      {
        model: IdCard,
        attributes: ["sex", "birthday", "address"],
        required: false,
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 用户详情
router.post("/detail", new Auth(16).m, async (ctx) => {
  const { uid } = ctx.request.body;
  const user = await User.findOne({ where: { uid } });
  if (!user) {
    throw new global.errs.NotFound("用户不存在");
  }
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: user,
  };
});

// 更新用户信息 
router.post("/update", new Auth(16).m, async (ctx, next) => {
  const { uid, pid, openid, point, inviteCode, ...res } = ctx.request.body;

  if (res.power >= ctx.auth.scope) {
    throw new global.errs.AuthFailed("权限不够");
  }



  if (res.avatar) {
    const userAvatar = await User.findOne({ where: { uid } });
    await Alioss.del(userAvatar.avatar);
  }

  const user = await User.update(res, {
    where: {
      uid,
    },
  });

  if (user[0] == 0) {
    throw new global.errs.AuthFailed("编辑失败");
  }

  redis.del(`token:${user.openid}`);
  

  ctx.body = {
    code: 200,
    msg: "编辑成功",
  };
});

// 获取用户粉丝列表
router.post("/fans/list", new Auth().m, async (ctx) => {
  const { page=1, pageSize=10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const { count: total, rows } = await User.findAndCountAll({
    where: { pid: ctx.auth.uid },
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "DESC"]], // 排序
  });

  ctx.body = {
    msg: "查询成功",
    code: 200,
    total,
    data: rows,
  };
});

module.exports = router;
